package cn.tedu.v1_1;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * 聊天室 Version  1.1
 * 服务器端  功能：1.服务器申请端口号软件具备端口号
 *               2.在start方法中 等待客户端连接  返回socket
 *                                IO读入
 *        【新增】3.所有服务器端异常 全部捕获 明确提示
 *               4.关闭severSocket
 */

public class Server {
    private ServerSocket  serverSocket;
    public Server(){
        try {
            serverSocket=new ServerSocket(1234);
            //BindException   端口号已被占用
        }catch (BindException e){
            System.out.println();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start()  {
        BufferedReader br = null;
        Socket socket = null;
        try{
        System.out.println("等待客户端的连接");
            socket = serverSocket.accept();
            System.out.println("一个客户端连接上了");
            InputStream is = null;
            //低级流---读入
            //高级流--转换流  目的：指定编码集：UTF8
            InputStreamReader isr = null;
            //高级流--缓冲输入流
         //   BufferedReader br = null;
            is = socket.getInputStream();
            isr = new InputStreamReader(is, "UTF8");
            br = new BufferedReader(isr);
            while (true) {
                String str = null;
                str = br.readLine();
                System.out.println("客户端："+str);
            }
        }catch (UnsupportedEncodingException e){
            System.out.println();
        }catch (SocketException e){
            System.out.println();
        }
        catch (IOException e) {
            System.out.println();
            }finally {
            if (br!=null){
                try {
                    br.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        }
    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
}
